<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>讲解员报名管理</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui@2.7.6/dist/css/layui.css">
    <style>
        .layui-table-cell {
            height: auto;
            line-height: 1.6;
        }
        .status-badge {
            padding: 2px 8px;
            border-radius: 3px;
            color: #fff;
            font-size: 12px;
        }
        .status-pending { background-color: #ff9800; }
        .status-approved { background-color: #4caf50; }
        .status-rejected { background-color: #f44336; }
        .detail-panel {
            padding: 20px;
            background: #f8f8f8;
            border-radius: 5px;
            margin-bottom: 15px;
        }
        .detail-item {
            margin-bottom: 10px;
        }
        .detail-label {
            font-weight: bold;
            color: #333;
            width: 120px;
            display: inline-block;
        }
        .text-ellipsis {
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    </style>
</head>
<body>
    <div class="layui-container" style="margin-top: 20px;">
        <div class="layui-row">
            <div class="layui-col-xs12">
                <!-- 页面标题和操作区 -->
                <div class="layui-card">
                    <div class="layui-card-header">
                        <h2>讲解员报名管理</h2>
                    </div>
                    <div class="layui-card-body">
                        <!-- 筛选条件 -->
                        <div class="layui-form layui-row layui-col-space10" lay-filter="searchForm">
                            <div class="layui-col-md2">
                                <select name="status" lay-filter="statusFilter">
                                    <option value="">全部状态</option>
                                    <option value="0">待审核</option>
                                    <option value="1">已通过</option>
                                    <option value="2">已拒绝</option>
                                </select>
                            </div>
                            <div class="layui-col-md2">
                                <select name="gender" lay-filter="genderFilter">
                                    <option value="">全部性别</option>
                                    <option value="male">男</option>
                                    <option value="female">女</option>
                                </select>
                            </div>
                            <div class="layui-col-md3">
                                <input type="text" name="department" placeholder="搜索院系" class="layui-input">
                            </div>
                            <div class="layui-col-md3">
                                <input type="text" name="search" placeholder="搜索姓名/手机号/学号" class="layui-input">
                            </div>
                            <div class="layui-col-md2">
                                <button class="layui-btn" lay-submit lay-filter="search">搜索</button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 申请列表 -->
                <div class="layui-card">
                    <div class="layui-card-body">
                        <table class="layui-hide" id="volunteerTable" lay-filter="volunteerTable"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 详情弹窗 -->
    <div id="detailModal" style="display: none; padding: 20px;">
        <div class="detail-panel">
            <div class="detail-item">
                <span class="detail-label">申请ID：</span>
                <span id="detail-id"></span>
            </div>
            <div class="detail-item">
                <span class="detail-label">用户ID：</span>
                <span id="detail-user-id"></span>
            </div>
            <div class="detail-item">
                <span class="detail-label">姓名：</span>
                <span id="detail-name"></span>
            </div>
            <div class="detail-item">
                <span class="detail-label">性别：</span>
                <span id="detail-gender"></span>
            </div>
            <div class="detail-item">
                <span class="detail-label">手机号：</span>
                <span id="detail-phone"></span>
            </div>
            <div class="detail-item">
                <span class="detail-label">学号：</span>
                <span id="detail-student-id"></span>
            </div>
            <div class="detail-item">
                <span class="detail-label">院系：</span>
                <span id="detail-department"></span>
            </div>
            <div class="detail-item">
                <span class="detail-label">年级：</span>
                <span id="detail-grade"></span>
            </div>
            <div class="detail-item">
                <span class="detail-label">相关经验：</span>
                <div id="detail-experience" style="margin-top: 10px; padding: 10px; background: white; border-radius: 5px; border: 1px solid #ddd;"></div>
            </div>
            <div class="detail-item">
                <span class="detail-label">可服务时间：</span>
                <div id="detail-time" style="margin-top: 10px; padding: 10px; background: white; border-radius: 5px; border: 1px solid #ddd;"></div>
            </div>
            <div class="detail-item">
                <span class="detail-label">自我介绍：</span>
                <div id="detail-introduction" style="margin-top: 10px; padding: 10px; background: white; border-radius: 5px; border: 1px solid #ddd;"></div>
            </div>
            <div class="detail-item">
                <span class="detail-label">申请时间：</span>
                <span id="detail-created"></span>
            </div>
            <div class="detail-item">
                <span class="detail-label">状态：</span>
                <span id="detail-status"></span>
            </div>
            <div class="detail-item" id="detail-note-container">
                <span class="detail-label">审核备注：</span>
                <div id="detail-note" style="margin-top: 10px; padding: 10px; background: white; border-radius: 5px; border: 1px solid #ddd;"></div>
            </div>
        </div>
    </div>

    <!-- 审核弹窗 -->
    <div id="reviewModal" style="display: none; padding: 20px;">
        <form class="layui-form" lay-filter="reviewForm">
            <input type="hidden" name="id" id="review-id">
            <div class="layui-form-item">
                <label class="layui-form-label">审核结果</label>
                <div class="layui-input-block">
                    <input type="radio" name="status" value="1" title="通过">
                    <input type="radio" name="status" value="2" title="拒绝">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">审核备注</label>
                <div class="layui-input-block">
                    <textarea name="review_note" placeholder="请输入审核备注..." class="layui-textarea" style="height: 100px;"></textarea>
                </div>
            </div>
        </form>
    </div>

    <script type="text/html" id="toolbarDemo">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm" lay-event="refresh">刷新数据</button>
            <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="batchApprove">批量通过</button>
            <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="batchReject">批量拒绝</button>
            <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="exportData">导出数据</button>
        </div>
    </script>

    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="detail">查看详情</a>
        {{# if(d.status == 0) { }}
        <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="review">审核</a>
        {{# } }}
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del">删除</a>
    </script>

    <script type="text/html" id="statusTpl">
        {{# if(d.status == 0) { }}
        <span class="status-badge status-pending">待审核</span>
        {{# } else if(d.status == 1) { }}
        <span class="status-badge status-approved">已通过</span>
        {{# } else { }}
        <span class="status-badge status-rejected">已拒绝</span>
        {{# } }}
    </script>

    <script src="https://cdn.jsdelivr.net/npm/layui@2.7.6/dist/layui.js"></script>
    <script>
        layui.use(['table', 'form', 'layer', 'laydate'], function(){
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;

            // 初始化表格
            table.render({
                elem: '#volunteerTable',
                url: '../api/admin/volunteer_management.php?action=list&token=admin_token',
                toolbar: '#toolbarDemo',
                defaultToolbar: ['filter', 'print', 'exports'],
                cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'id', title: 'ID', width: 70, fixed: 'left'},
                    {field: 'user_id', title: '用户ID', width: 80},
                    {field: 'name', title: '姓名', width: 100},
                    {field: 'gender', title: '性别', width: 80, templet: function(d) {
                        return d.gender === 'male' ? '男' : '女';
                    }},
                    {field: 'phone', title: '手机号', width: 120},
                    {field: 'student_id', title: '学号', width: 120},
                    {field: 'department', title: '院系', width: 150, templet: function(d) {
                        return d.department ? '<div class="text-ellipsis" title="' + d.department + '">' + d.department + '</div>' : '未填写';
                    }},
                    {field: 'grade', title: '年级', width: 80},
                    {field: 'status', title: '状态', width: 100, templet: '#statusTpl'},
                    {field: 'created_at', title: '申请时间', width: 160},
                    {title: '操作', width: 200, toolbar: '#barDemo', fixed: 'right'}
                ]],
                page: true,
                height: 'full-220',
                cellMinWidth: 80,
                parseData: function(res) {
                    if (res.code === 200) {
                        return {
                            "code": 0,
                            "msg": "",
                            "count": res.data?.pagination?.total || 0,
                            "data": res.data?.list || []
                        };
                    } else {
                        layer.msg(res.message || '加载失败');
                        return {
                            "code": 1,
                            "msg": res.message || '加载失败',
                            "count": 0,
                            "data": []
                        };
                    }
                }
            });

            // 头工具栏事件
            table.on('toolbar(volunteerTable)', function(obj){
                var checkStatus = table.checkStatus(obj.config.id);
                switch(obj.event){
                    case 'refresh':
                        table.reload('volunteerTable');
                        break;
                    case 'batchApprove':
                        var data = checkStatus.data;
                        if(data.length === 0){
                            layer.msg('请先选择数据');
                            return;
                        }
                        batchReview(data, 1, '通过');
                        break;
                    case 'batchReject':
                        var data = checkStatus.data;
                        if(data.length === 0){
                            layer.msg('请先选择数据');
                            return;
                        }
                        batchReview(data, 2, '拒绝');
                        break;
                    case 'exportData':
                        layer.msg('导出功能开发中...');
                        break;
                }
            });

            // 监听行工具事件
            table.on('tool(volunteerTable)', function(obj){
                var data = obj.data;
                switch(obj.event){
                    case 'detail':
                        showDetail(data);
                        break;
                    case 'review':
                        showReviewModal(data.id);
                        break;
                    case 'del':
                        layer.confirm('确定要删除这个申请吗？', function(index){
                            deleteApplication(data.id, function() {
                                obj.del();
                                layer.close(index);
                                layer.msg('删除成功');
                            });
                        });
                        break;
                }
            });

            // 搜索表单提交
            form.on('submit(search)', function(data){
                table.reload('volunteerTable', {
                    where: data.field,
                    page: {curr: 1}
                });
                return false;
            });

            // 状态筛选
            form.on('select(statusFilter)', function(data){
                table.reload('volunteerTable', {
                    where: {status: data.value},
                    page: {curr: 1}
                });
            });

            // 性别筛选
            form.on('select(genderFilter)', function(data){
                table.reload('volunteerTable', {
                    where: {gender: data.value},
                    page: {curr: 1}
                });
            });

            // 显示详情
            function showDetail(data) {
                document.getElementById('detail-id').textContent = data.id;
                document.getElementById('detail-user-id').textContent = data.user_id;
                document.getElementById('detail-name').textContent = data.name;
                document.getElementById('detail-gender').textContent = data.gender === 'male' ? '男' : '女';
                document.getElementById('detail-phone').textContent = data.phone;
                document.getElementById('detail-student-id').textContent = data.student_id || '未填写';
                document.getElementById('detail-department').textContent = data.department || '未填写';
                document.getElementById('detail-grade').textContent = data.grade || '未填写';
                document.getElementById('detail-experience').textContent = data.experience || '无';
                document.getElementById('detail-time').textContent = data.available_time || '未填写';
                document.getElementById('detail-introduction').textContent = data.self_introduction || '无';
                document.getElementById('detail-created').textContent = data.created_at;

                var statusMap = {0: '待审核', 1: '已通过', 2: '已拒绝'};
                var statusClass = {0: 'status-pending', 1: 'status-approved', 2: 'status-rejected'};
                document.getElementById('detail-status').innerHTML = 
                    '<span class="status-badge ' + statusClass[data.status] + '">' + statusMap[data.status] + '</span>';

                // 审核备注
                if (data.review_note) {
                    document.getElementById('detail-note').textContent = data.review_note;
                    document.getElementById('detail-note-container').style.display = 'block';
                } else {
                    document.getElementById('detail-note-container').style.display = 'none';
                }

                layer.open({
                    type: 1,
                    title: '申请详情',
                    area: ['800px', '700px'],
                    content: document.getElementById('detailModal').innerHTML,
                    shadeClose: true
                });
            }

            // 显示审核弹窗
            function showReviewModal(id) {
                document.getElementById('review-id').value = id;
                layer.open({
                    type: 1,
                    title: '审核申请',
                    area: ['500px', '300px'],
                    content: document.getElementById('reviewModal').innerHTML,
                    btn: ['提交', '取消'],
                    yes: function(index) {
                        var status = layer.getChildFrame('input[name="status"]:checked', index).val();
                        var note = layer.getChildFrame('textarea[name="review_note"]', index).val();
                        
                        if (!status) {
                            layer.msg('请选择审核结果');
                            return;
                        }
                        
                        reviewApplication({
                            id: id,
                            status: parseInt(status),
                            review_note: note
                        }, function() {
                            layer.close(index);
                            table.reload('volunteerTable');
                        });
                    }
                });
            }

            // 审核申请
            function reviewApplication(data, callback) {
                fetch('../api/admin/volunteer_management.php?action=review&token=admin_token', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data)
                })
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        layer.msg(result.message || '审核成功');
                        if (callback) callback();
                    } else {
                        layer.msg(result.message || '审核失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    layer.msg('审核失败');
                });
            }

            // 批量审核
            function batchReview(data, status, statusText) {
                layer.confirm('确定要批量' + statusText + '选中的申请吗？', function(index){
                    var ids = data.map(item => item.id);
                    fetch('../api/admin/volunteer_management.php?action=batch_review&token=admin_token', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            ids: ids,
                            status: status,
                            review_note: '批量' + statusText
                        })
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.code === 200) {
                            layer.close(index);
                            layer.msg(result.message || '批量' + statusText + '成功');
                            table.reload('volunteerTable');
                        } else {
                            layer.msg(result.message || '批量' + statusText + '失败');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        layer.msg('批量' + statusText + '失败');
                    });
                });
            }

            // 删除申请
            function deleteApplication(id, callback) {
                fetch('../api/admin/volunteer_management.php?id=' + id + '&token=admin_token', {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(result => {
                    if (result.code === 200) {
                        if (callback) callback();
                    } else {
                        layer.msg(result.message || '删除失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    layer.msg('删除失败');
                });
            }
        });
    </script>
</body>
</html>